<?php


namespace app\common\model\merchant;


use app\common\model\BaseModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use yiqiniu\extend\exception\ApiException;

/**
 * 会员积分流水
 * Class MembersPoint
 * @package app\model
 */
class MembersPointModel extends BaseModel
{
    //
    public string $fieldId = 'id';

    //
    public string $fieldMerId = 'mer_id';
    // 所属商户
    public string $fieldMemberId = 'member_id';
    // 会员编号
    public string $fieldPoint = 'point';
    // 变动积分
    public string $fieldRePoint = 're_point';
    // 变动后积分
    public string $fieldVpId = 'vp_id';
    // 关联活动
    public string $fieldMemo = 'memo';
    // 备注
    public string $fieldCreateAt = 'create_at';
    // 创建时间
    protected $name = 'members_point';

    // 设置字段信息
    protected $schema = [
        'id' => 'int',        //
        'mer_id' => 'string',        // 所属商户
        'member_id' => 'int',        // 会员编号
        'point' => 'int',        // 变动积分
        're_point' => 'int',        // 变动后积分
        'vp_id' => 'int',        // 关联活动
        'memo' => 'string',        // 备注
        'create_at' => 'datetime',        // 创建时间
    ];

    /**
     * 会员调整积分
     * @param int $member_id
     * @param string $mer_id
     * @param $point
     * @throws Exception
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function saveMemberPoint(int $member_id, string $mer_id , $point ,$type = 1, $memo= ''): void
    {

        try {
            $info = $this->db('merchant_members')->where('mer_id', $mer_id)->where('member_id', $member_id)
                ->find();
            if (empty($info)) {
                throw  new Exception('会员不存在或已删除',API_ERROR);
            }
            $this->db()->startTrans();
            $re_point = $info['point'] + $point;
            if ((int)$type === 2) {
                $re_point = $info['point'] - $point;
                if ($re_point < 0) {
                    throw  new Exception('积分不足',API_ERROR);
                }
            }

            $this->db('merchant_members')->where('mer_id', $mer_id)->where('member_id', $member_id)
                ->update(['point' => $re_point]);
            $this->db()->insert([
                'mer_id' => $mer_id,
                'member_id' => $member_id,
                'point' => $point,
                're_point' => $re_point,
                'memo' => $memo,
                'type' => $type,
            ]);
            $this->db()->commit();
        } catch (Exception $e) {
            $this->db()->rollback();
            throw $e;
        }
    }
}
